package com.hnkywl.jip.dao;

import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.sql.*;

@Repository
public class VoucherDao extends SimpleHibernateTemplate {
    public Boolean beginGenerateVoucher(Integer id, VoucherType type) {
        String sql = "update " + type.getTable() + " set jiuqi_insert_flag=2 where " + type.getPk() + "=? and isnull(jiuqi_insert_flag,1)=1";
        int updateRows = createSQLQuery(sql, id).executeUpdate();
        return updateRows == 0 ? false : true;
    }

    public Boolean beginRevokeVoucher(Integer id, VoucherType type) {
        String sql = "update " + type.getTable() + " set jiuqi_delete_flag=2 where " + type.getPk() + "=? and jiuqi_insert_flag=3";
        int updateRows = createSQLQuery(sql, id).executeUpdate();
        return updateRows == 0 ? false : true;
    }

    public Boolean generateVoucherSuccess(String uuid, String voucherId, String voucherNum, Integer acctyear, Integer id, VoucherType type) {
        String sql = "update " + type.getTable() + " set jiuqi_uuid=?,jiuqi_voucher_id=?,jiuqi_voucher_num=?,jiuqi_acctyear=?,jiuqi_insert_flag=3,jiuqi_delete_flag=1 where " + type.getPk() + "=? and jiuqi_insert_flag=2";
        int updateRows = createSQLQuery(sql, uuid, voucherId, voucherNum, acctyear, id).executeUpdate();
        return updateRows == 0 ? false : true;
    }

    public Boolean revokeVoucherSuccess(Integer id, VoucherType type) {
        String sql = "update " + type.getTable() + " set jiuqi_delete_flag=3,jiuqi_insert_flag=1 where " + type.getPk() + "=? and jiuqi_insert_flag=3 and jiuqi_delete_flag=2";
        int updateRows = createSQLQuery(sql, id).executeUpdate();
        return updateRows == 0 ? false : true;
    }

    public String restVoucher(Integer userId, Integer id, Integer type) throws SQLException {
        Session session = getSession();
        Connection conn = session.connection();
        CallableStatement call = conn.prepareCall("{call sp_jiuqi_voucher_rest(?,?,?,?)}");
        call.setInt(1, userId);
        call.setInt(2, id);
        call.setInt(3, type);
        call.registerOutParameter(4, Types.VARCHAR);
        call.execute();
        return call.getString(4);
    }
}
